"""3.2 【stdio模式】mcp客户端开发—连接服务端"""
import asyncio
from contextlib import AsyncExitStack

from mcp import StdioServerParameters, stdio_client, ClientSession


class MCPClient:



    def __init__(self):
        self.async_exit_stack = AsyncExitStack()
        self.session = None


    async def connect_to_server(self,server_path):
        # 一、创建服务连接的参数
        server_parameters = StdioServerParameters(
            command="python",
            args=[server_path],
            env=None
        )
        # 二、创建stdio_client
        client = stdio_client(server_parameters)
        transport = await self.async_exit_stack.enter_async_context(client)
        read_stream, write_stream = transport
        # 三、创建会话client
        client_session = ClientSession(read_stream, write_stream)
        self.session = await self.async_exit_stack.enter_async_context(client_session)
        # 四、初始化会话
        await self.session.initialize()
        # 五、获取资源列表
        tools = await self.session.list_tools()
        print(tools)

    #关闭资源
    async def aclose(self):
        await self.async_exit_stack.aclose()

async def main():
    client = MCPClient()
    try:
        await client.connect_to_server("server.py")
    except Exception as e:
        print(f"连接失败: {e}")
        return
    finally:
        await client.aclose()

if __name__ == "__main__":
    asyncio.run(main())